import os
import requests
import base64
import json
import numpy as np
from typing import Optional
from dotenv import load_dotenv

load_dotenv()

class BaiduASRClient:
    """百度语音识别API客户端"""

    def __init__(self):
        # 百度语音识别API配置
        self.api_key = os.getenv("BAIDU_API_KEY")  # 你的API Key
        self.secret_key = os.getenv("BAIDU_SECRET_KEY")  # 你的Secret Key
        self.access_token = None

        # API URLs
        self.token_url = "https://aip.baidubce.com/oauth/2.0/token"
        self.asr_url = "https://vop.baidu.com/server_api"

        # 获取access_token
        self.__get_access_token__()

    def __get_access_token__(self):
        try:
            params = {
                'grant_type': 'client_credentials',
                'client_id': self.api_key,
                'client_secret': self.secret_key
            }

            response = requests.post(self.token_url, params=params)
            result = response.json()

            if 'access_token' in result:
                self.access_token = result['access_token']
                print("成功获取access_token")
            else:
                print(f"获取access_token失败: {result}")

        except Exception as e:
            print(f"获取access_token异常: {e}")

    def recognize_audio(self, audio_data: np.ndarray, sample_rate: int = 16000) -> Optional[str]:

        if not self.access_token:
            print("没有有效的access_token，无法进行语音识别")
            return None

        try:
            # 将numpy数组转换为字节
            audio_bytes = audio_data.tobytes()

            # Base64编码
            audio_base64 = base64.b64encode(audio_bytes).decode('utf-8')

            # 构建请求数据
            data = {
                'format': 'pcm',
                'rate': sample_rate,
                'channel': 1,
                'cuid': 'python_client',
                'token': self.access_token,
                'speech': audio_base64,
                'len': len(audio_bytes)
            }

            # 设置请求头
            headers = {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            }

            # print("正在发送语音识别请求...")
            response = requests.post(
                self.asr_url,
                data=json.dumps(data),
                headers=headers,
                timeout=30
            )

            result = response.json()
            # print(f"API响应: {result}")

            # 解析结果
            if result.get('err_no') == 0 and 'result' in result:
                if result['result']:
                    text = result['result'][0]
                    # print(f"识别结果: {text}")
                    return text
                else:
                    print("识别结果为空")
                    return ""
            else:
                error_msg = result.get('err_msg', '未知错误')
                print(f"语音识别失败: {error_msg} (错误码: {result.get('err_no')})")
                return None

        except Exception as e:
            print(f"语音识别异常: {e}")
            return None


def baidu_asr_send(recording: np.ndarray, sample_rate: int) -> Optional[str]:
    client = BaiduASRClient()
    return client.recognize_audio(recording, sample_rate)